package com.haochang.chunkvod.app.utils;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.config.ServerConfig;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DownLoadObserver;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

/**
 * @author Yangjie
 *         className UpdateUtil
 *         created at  2016/9/26  18:18
 *         版本更新util
 */
public class UpdateUtil
{
	private static volatile UpdateUtil instanse;

	public UpdateUtil()
	{
	}

	//懒加载“双检锁”机制
	public static UpdateUtil getInstanse()
	{
		if (null == instanse)
		{
			synchronized (UpdateUtil.class)
			{
				if (null == instanse)
				{
					instanse = new UpdateUtil();
				}
			}
		}
		return instanse;
	}

	public void requestUpdateVersion(final BaseActivity activity, final Handler progressHandler)
	{
		new HostessData(activity).requestUpdateVersion(new HostessData.ResultResponseJSONObject()
		{
			@Override
			public void onRequestSuccess(JSONObject jsonObject)
			{
				jsonObjectUpdate = jsonObject;
				//先显示dialog,确定后下载
				int localCode = PackageManagerUtil.getInstance().getVersionCode(activity);
				int serverCode = jsonObject.optInt("code");
				if (serverCode > localCode)
				{//服务器的versionCode比本地大
					if (!RequestPermissionsUtil.getInstance().checkPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
							RequestPermissionsUtil.PERMISSION_WRITE_EXTERNAL_STORAGE))//判断是否获取权限
					{
						//这个是能获取权限
						int state = DownLoadManagerUtils.getInstance().queryDownloadStatus(activity, HelperUtils.getHelperInstance()
								.getLValue(HelperUtils.getHelperInstance().getSValue(DownLoadManagerUtils.DownLoad_FileName, ""), 0));
						//状态为 （状态未知||新建||恢复下载||下载失败||下载暂停（下载成功且安装包不能安装）） 就重新开始下载
						//hasInstallableApk这个方法会直接安装可用apk
						if (state == DownLoadManagerUtils.DOWNLOAD_STATE_UNKNOW || state == DownLoadManagerUtils.DOWNLOAD_STATE_SHOULD_BEGEIN
								|| state == DownLoadManagerUtils.DOWNLOAD_STATE_RESUME || state == DownloadManager.STATUS_FAILED
								|| state == DownloadManager.STATUS_PAUSED || (state == DownloadManager.STATUS_SUCCESSFUL
										&& !DownLoadManagerUtils.getInstance().hasInstallableApk(activity, DownLoadManagerUtils.getInstance().tempPath)))
						{//创建新的下载
							showUpdateDialog(activity, progressHandler);
						} else if (state == DownloadManager.STATUS_RUNNING)
						{//状态为正在下载，则将绑定handler
							startDownLoad(activity, new JSONObject(), progressHandler);
						}
					}
				}
			}

			@Override
			public void onFail(int errorNo, String errorMsg)
			{
			}
		});
	}

	public void showUpdateDialog(final BaseActivity activity, final Handler progressHandler)
	{
		String[] content = null;
		String currentVersionName = PackageManagerUtil.getInstance().getVersion(activity);
		String newVersionName;
		if (jsonObjectUpdate != null)
		{
			newVersionName = jsonObjectUpdate.optString("version");
			JSONArray updateItem = jsonObjectUpdate.optJSONArray("description");
			if (null != updateItem && updateItem.length() > 0)
			{
				int len = updateItem.length();
				content = new String[len];
				for (int i = 0; i < len; i++)
				{
					content[i] = updateItem.optString(i);
				}
			}
		} else
		{
			return;
		}
		View view = LayoutInflater.from(activity).inflate(R.layout.inflate_update, null);
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				(int) (ScreenUtils.getScreenWidth(activity) * 0.618));
		view.setLayoutParams(params);
		final AlertDialog mDialog = new AlertDialog.Builder(activity).create();
		BaseTextView tv_title = (BaseTextView) view.findViewById(R.id.tv_title);
		BaseTextView desc = (BaseTextView) view.findViewById(R.id.desc);
		BaseTextView tvSure = (BaseTextView) view.findViewById(R.id.tv_ensure);
		BaseTextView tvCancel = (BaseTextView) view.findViewById(R.id.tv_cancel);
		StringBuffer sb = new StringBuffer();
		sb.append("●当前版本:");
		sb.append(currentVersionName);
		sb.append("\n\n●发现新版本:");
		sb.append(newVersionName);
		sb.append("\n\n●更新：");
		if (content != null && content.length > 0)
		{
			int len = content.length;
			for (int i = 0; i < len; i++)
			{
				if (!TextUtils.isEmpty(content[i]))
				{
					sb.append("\n" + "\t\t\t\t\t\t\t" + (i + 1) + " : " + content[i] + "\n");
				}
			}
		}
		sb.append("\n●是否更新?" + "\n");
		desc.setText(sb.toString());
		tvSure.setOnClickListener(new OnBaseClickListener()
		{
			@Override
			public void onBaseClick(View v)
			{
				UpdateUtil.getInstanse().startDownLoad(activity, UpdateUtil.getInstanse().jsonObjectUpdate, progressHandler);
				mDialog.dismiss();
			}
		});
		tvCancel.setOnClickListener(new OnBaseClickListener()
		{
			@Override
			public void onBaseClick(View v)
			{
				mDialog.dismiss();
			}
		});
		mDialog.show();

		Window window = mDialog.getWindow();
		WindowManager.LayoutParams layoutParams = window.getAttributes();
		layoutParams.width = ScreenUtils.getScreenWidth(activity);
		window.setAttributes(layoutParams);
		window.setGravity(Gravity.BOTTOM);

		window.setBackgroundDrawable(new ColorDrawable(0));
		window.setContentView(view);
		mDialog.setCancelable(true);
		mDialog.setCanceledOnTouchOutside(false);
	}

	public JSONObject jsonObjectUpdate;

	public void startDownLoad(final BaseActivity activity, JSONObject jsonObject, Handler progressHandler)
	{
		Logger.e("startDownLoadstartDownLoad");
		String versionName = "";
		int versionCode;
		String downLoadUrl = "";
		if (null != jsonObject)
		{
			versionName = jsonObject.optString("version");
			versionCode = jsonObject.optInt("code");
			downLoadUrl = ServerConfig.UPDATE_VERSION + jsonObject.optString("url");
		}
		//		versionName = "1.0.2";
		//		downLoadUrl = "http://shouji.360tpcdn.com/160914/fa03ac88a1e38d4add337a0b7843ca0e/com.wuba.bangjob_6003002.apk";
		String fileName = "vod" + versionName + ".apk";
		String notifyTitle = "升级vod" + versionName;
		if (!TextUtils.isEmpty(versionName) && !TextUtils.isEmpty(downLoadUrl) && !TextUtils.isEmpty(notifyTitle))
		{
			int status = DownLoadManagerUtils.getInstance().requestDownLoad(activity, downLoadUrl, fileName, notifyTitle);
			if (DownLoadManagerUtils.DOWNLOAD_STATE_SHOULD_BEGEIN == status || status == DownloadManager.STATUS_RUNNING)
			{
				//监听下载进度条
				activity.getContentResolver().registerContentObserver(Uri.parse("content://downloads/"), true, new DownLoadObserver(progressHandler, activity,
						HelperUtils.getHelperInstance().getLValue(HelperUtils.getHelperInstance().getSValue(DownLoadManagerUtils.DownLoad_FileName, ""), 0)));
				ToastUtils.showText(activity, "正在下载...");
			}
		}
	}

	public void installAPK(Context context, String path)
	{
		if (HelperUtils.getHelperInstance().getBValue(DownLoadManagerUtils.SDAvailable, false))
		{
			PackageManagerUtil.getInstance().installApk(context, path);// SD卡可用
		} else
		{
			File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), DownloadManager.COLUMN_TITLE);
			if (file.exists())
			{
				PackageManagerUtil.getInstance().installApk(context, file.getPath());
			}
		}
	}
}
